// warnning: this file is not use for login
import { NextResponse } from "next/server";
import connect from "@/utils/mongodb";
import User from "@/model/User";
import bcrypt from "bcryptjs";
import { sendLoginNotification } from "@/services/emailService";
import { v4 as uuidv4 } from "uuid"; // 新增：使用uuid生成唯一ID

// 获取客户端信息
const getClientInfo = (request) => {
  const ip = request.headers.get("x-forwarded-for")?.split(",")[0] ||
    request.headers.get("x-real-ip") ||
    "未知IP";
  const userAgent = request.headers.get("user-agent") || "未知设备";
  console.debug("获取到的ip地址: ", ip)
  console.debug("获取到的设备信息: ", userAgent)
  return { ip, device: userAgent };
};

export const POST = async (request) => {
  try {
    const { email, password } = await request.json();

    if (!email || !password) {
      return NextResponse.json(
        { message: "请输入邮箱和密码" },
        { status: 400 }
      );
    }

    await connect();

    // 查找用户
    const user = await User.findOne({ email });
    if (!user) {
      return NextResponse.json(
        { message: "邮箱或密码错误" },
        { status: 401 }
      );
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return NextResponse.json(
        { message: "邮箱或密码错误" },
        { status: 401 }
      );
    }

    // 获取客户端信息
    const { ip, device } = getClientInfo(request);
    const now = new Date();

    // 新增：对比注册IP（首次登录时）
    const isFirstLogin = !user.lastLogin;
    const isRegisterIpDifferent = isFirstLogin && user.registerIp && user.registerIp !== ip;

    // 发送通知的条件：首次登录且注册IP与当前IP不同 或 非首次登录但IP/设备变更
    if (
      (isFirstLogin && isRegisterIpDifferent) ||
      (!isFirstLogin && (isNewIp || isNewDevice))
    ) {
      sendLoginNotification(
        email,
        user.name,
        ip,
        device,
        now,
        user.lastLogin?.ipAddress || user.registerIp || "无记录", // 首次登录时显示注册IP
        user.lastLogin?.deviceInfo || "未知设备"
      ).catch(err => console.error("邮件发送失败:", err));
    }

    // 生成唯一会话ID（使用uuid确保唯一性）
    const sessionId = uuidv4();

    // 更新用户信息（关键修复）
    user.lastLogin = {
      ipAddress: ip,
      deviceInfo: device,
      timestamp: now
    };

    // 维护最近5个会话（修复数组操作逻辑）
    user.sessions = [
      ...user.sessions.filter(s => s), // 过滤无效会话
      { sessionId, deviceInfo: device, ipAddress: ip, createdAt: now }
    ]
      .sort((a, b) => b.createdAt - a.createdAt) // 按时间倒序
      .slice(0, 5); // 保留最近5个

    // 强制保存（确保更新生效）
    await user.save({ validateBeforeSave: true });

    return NextResponse.json({
      message: "登录成功",
      success: true,
      user: { id: user._id, name: user.name, email: user.email }
    });

  } catch (error) {
    console.error("登录接口错误:", error);
    return NextResponse.json(
      { message: "登录失败，请稍后再试" },
      { status: 500 }
    );
  }
};